﻿
using System;
using System.Drawing;
using DevExpress.XtraEditors;
using System.Windows.Forms;
using System.Reflection;
using DevExpress.XtraTab;
using DevExpress.XtraTreeList;
using System.Collections;
using System.Collections.Generic;
using DevExpress.XtraTreeList.Nodes;

using DevExpress.XtraEditors.Controls;
using DevExpress.XtraBars.Docking;
using DevExpress.XtraBars;
using efuture.http;
using efuture.xml;
using System.IO;
using efuture.utils;

namespace efuture.vdrp.main
{

    public partial class frmMain : XtraForm, IPluginContext
    {

        public frmMain()
        {
            InitializeComponent();
            this.tabWorkArea.HeaderButtons =
                ((DevExpress.XtraTab.TabButtons)((((DevExpress.XtraTab.TabButtons.Prev | DevExpress.XtraTab.TabButtons.Next)

           | DevExpress.XtraTab.TabButtons.Close)

           | DevExpress.XtraTab.TabButtons.Default)));

            this.tabWorkArea.HeaderButtonsShowMode = DevExpress.XtraTab.TabButtonShowMode.Always;
        }


        #region Skins

        void InitSkins()
        {
            barManager.ForceInitialize();
            if (barManager.GetController().PaintStyleName == "Skin")
            {
                iPaintStyle.Caption = skinMask + DevExpress.LookAndFeel.UserLookAndFeel.Default.ActiveSkinName;
                iPaintStyle.Hint = iPaintStyle.Caption;
            }
            foreach (DevExpress.Skins.SkinContainer cnt in DevExpress.Skins.SkinManager.Default.Skins)
            {
                BarButtonItem item = new BarButtonItem(barManager, skinMask + cnt.SkinName);//
                item.Name = "bi" + cnt.SkinName;
                item.Id = barManager.GetNewItemId();
                iPaintStyle.AddItem(item);
                item.ItemClick += new ItemClickEventHandler(OnSkinClick);
            }
        }
        void OnSkinClick(object sender, ItemClickEventArgs e)
        {
            string skinName = e.Item.Caption.Replace(skinMask, "");
            DevExpress.LookAndFeel.UserLookAndFeel.Default.SetSkinStyle(skinName);
            //barManager.GetController().PaintStyleName = "Skin";
            // solutionExplorer1.barManager.GetController().PaintStyleName = "Skin";
            //iPaintStyle.Caption = e.Item.Caption;
            //iPaintStyle.Hint = iPaintStyle.Caption;
            //iPaintStyle.ImageIndex = -1;
        }
        #endregion

        string skinMask = "Skin: ";
        Cursor currentCursor;
        private void treeList1_GetStateImage(object sender, DevExpress.XtraTreeList.GetStateImageEventArgs e)
        {

            if (e.Node.HasChildren)
            {
                e.Node.StateImageIndex = 6;
            }
            else
            {
                if (String.IsNullOrEmpty(Convert.ToString(e.Node[colDllName])))
                {
                    e.Node.StateImageIndex = 6;
                }
                else
                {
                    e.Node.StateImageIndex = 7;
                }
            }

        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            //treeList1.Nodes.FirstNode.Expanded = true;
            treeList3.Nodes.FirstNode.Expanded = true;
            treeList4.Nodes.FirstNode.Expanded = true;
            //treeList1.Nodes[1].Expanded = true;

        }

        private void treeList1_DoubleClick(object sender, EventArgs e)
        {
            if (treeList1.FocusedNode == null) return;
            if (treeList1.FocusedNode.HasChildren) return;

            Dictionary<String, String> p = new Dictionary<string, string>();
            String fullPath = "";
            String dllName = Convert.ToString(treeList1.FocusedNode[colDllName]);

            if (dllName.EndsWith(".table"))
            {
                fullPath = Application.StartupPath + "\\" + "RPTTable.dll";
                p.Add("ReportId", dllName.Split('.')[0]);
            }
            else if (dllName.EndsWith(".pivot"))
            {
                fullPath = Application.StartupPath + "\\" + "RPTPivot.dll";
                p.Add("ReportId", dllName.Split('.')[0]);
            }
            else
            {
                fullPath = Application.StartupPath + "\\" + dllName;
            }

            //只能开一个窗口
            for (int i = 0; i < tabWorkArea.TabPages.Count; i++)
            {
                string s = tabWorkArea.TabPages[i].Text;
                if (s == treeList1.FocusedNode.GetDisplayText(colMenuName))
                {
                    tabWorkArea.SelectedTabPage = tabWorkArea.TabPages[i];
                    return;
                }
            }

            if (!File.Exists(fullPath))
            {
                MessageBox.Show(fullPath + "不存在，不能加载！");
                return;
            }


            //MessageBox.Show(fullPath);

            Assembly MyAssembly = Assembly.LoadFile(fullPath);
            XtraForm myForm = (XtraForm)MyAssembly.CreateInstance("efuture.vdrp.frmMain");
            StartupResult result = StartupResult.Success;

            if (typeof(IPlugin).IsAssignableFrom(myForm.GetType()))
            {
                p.Add("serverURL", HttpHelper.serverURL);

                ((IPlugin)myForm).afterPropertiesSet(p);
                result = ((IPlugin)myForm).startup(this);
            }

            if (result == StartupResult.Success)
            {
                XtraTabPage newTab = tabWorkArea.TabPages.Add();
                newTab.Text = "  " + treeList1.FocusedNode.GetDisplayText(colMenuName);
                tabWorkArea.SelectedTabPage = newTab;
                myForm.TopLevel = false;
                myForm.Parent = newTab;
                myForm.Dock = DockStyle.Fill;
                myForm.FormBorderStyle = FormBorderStyle.None;
                myForm.Show();
            }
            else
            {
                MessageBox.Show(" load plugin failed");
            }
        }

        private void xtraTabControl1_CloseButtonClick(object sender, EventArgs e)
        {

        }

        private void textEdit1_EditValueChanged(object sender, EventArgs e)
        {
            treeList1.FilterNodes();
        }

        private void treeList1_FilterNode(object sender, FilterNodeEventArgs e)
        {
            String nodeText = Convert.ToString(e.Node[colMenuName]);
            bool IsVisible = nodeText.Contains(textEdit1.Text) && !e.Node.HasChildren;

            if (IsVisible)
            {
                TreeListNode Node = e.Node.ParentNode;

                while (Node != null)
                {
                    Node.Visible = IsVisible;
                    Node.Expanded = textEdit1.Text.Trim().Length > 0;
                    Node = Node.ParentNode;
                }
            }

            e.Node.Visible = IsVisible;
            e.Handled = true;

        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            String url = String.Format("/sys/user/menu/find?userId={0}", HttpHelper.userId);
            String xmlData = HttpHelper.DoGet(url, null);

            XMLHelper.BindingData(pnlMyMenu, new StringReader(xmlData), "/Root");
            InitSkins();
        }

        private void Layouts_ItemClick(object sender, ItemClickEventArgs e)
        {

        }


        private void Refresh(bool isWait)
        {
            if (isWait)
            {
                currentCursor = Cursor.Current;
                Cursor.Current = Cursors.WaitCursor;
            }
            else
                Cursor.Current = currentCursor;
            this.Refresh();
        }

        private void iSaveLayouts_ItemClick(object sender, ItemClickEventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Filter = "XML files (*.xml)|*.xml";
            dlg.Title = "Save Layout";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                Refresh(true);
                barManager.SaveToXml(dlg.FileName);
                Refresh(false);
            }
        }

        private void iLoadLayouts_ItemClick(object sender, ItemClickEventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "XML files (*.xml)|*.xml|All files|*.*";
            dlg.Title = "Restore Layout";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                Refresh(true);
                try
                {
                    barManager.RestoreFromXml(dlg.FileName);
                }
                catch { }
                Refresh(false);
            }
        }

        private void barButtonItem7_ItemClick(object sender, ItemClickEventArgs e)
        {
            //
        }


        #region IPluginContext 成员

        public void OnEvent(EventType e)
        {
            switch (e)
            {
                case EventType.OnClosed:
                    tabWorkArea.TabPages.Remove(tabWorkArea.SelectedTabPage);
                    tabWorkArea.SelectedTabPage = tabWorkArea.TabPages[tabWorkArea.TabPages.Count - 1];
                    break;
                default: break;
            }
        }

        #endregion

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            //
        }





        private void tabWorkArea_MouseDoubleClick(object sender, MouseEventArgs e)
        {

        }

        private void tabWorkArea_CloseButtonClick(object sender, EventArgs e)
        {
            if (tabWorkArea.TabPages.Count > 1)
            {
                //xtraTabControl1.TabPages.Remove(this.xtraTabControl1.SelectedTabPage);
                tabWorkArea.TabPages.Remove(tabWorkArea.SelectedTabPage);
                tabWorkArea.SelectedTabPage = tabWorkArea.TabPages[tabWorkArea.TabPages.Count - 1];
            }
        }
    }
}